package com.xrui.hbasecmd;

import com.xrui.hbase.ColumnName;
import com.xrui.hbase.tools.BaseTool;
import com.xrui.hbasecmd.config.ClusterConfig;
import com.xrui.hbasecmd.config.ConnectionDetails;
import com.xrui.hbasecmd.config.GlobalConfig;
import com.xrui.hbasecmd.data.ColumnType;
import com.xrui.hbasecmd.data.DataRow;
import com.xrui.hbasecmd.hbase.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CommandTool extends BaseTool {
    private static final Logger LOG = LoggerFactory.getLogger(CommandTool.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return "commander";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getDescription() {
        return "View hbase table data.";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getCategory() {
        return "Data";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected int run(List<String> nonFlagArgs) throws Exception {
        ConnectionDetails connectionDetails = getConnectionDetails("Thebe");
        if (connectionDetails == null) {
            return -1;
        }
        try {
            int count = 1;
            boolean canConnect = false;
            while(!(connectionDetails.canConnect()  )) {

                count ++ ;
                if( count > 3) {

                    break;
                }

            }
            if (count < 3) {
                canConnect = true;
            }
            if(canConnect){
                Connection connection = ConnectionManager.get().create(connectionDetails);
                Collection<String> tables;
                tables = connection.getTables().stream().filter(
                        it -> !TableUtil.isMetaTable(it)).collect(Collectors.toList()
                );

                tables.stream().forEach(table -> System.out.println(table));

                ClusterConfig clusterConfig = new ClusterConfig(connection.getServerName());
                clusterConfig.setConnection(connection.getConnectionDetails());
                String tableselected = "ecpcisqeddscat:ecp_ICW_Identifier";
                Collection<ColumnName> allColumnNames = clusterConfig.getColumnNames(tableselected);

                if (allColumnNames.isEmpty()) {
                    LOG.debug("Cache miss for table column names");
                    allColumnNames = connection.getTableLayout(tableselected).getColumns();
                } else {
                    LOG.debug("Cache hit for table column names");
                }

                QueryScanner scanner = null;
                if (allColumnNames.size() > 0) {
                     ColumnName columnName = allColumnNames.iterator().next();
                    if (scanner == null) {
                        scanner = connection.getScanner(tableselected, columnName);
                    }
                    scanner.setColumnName(columnName);
                    clusterConfig.setColumnNames(tableselected, allColumnNames);

                    Map<String, ColumnType> columnTypes;
                    columnTypes = new HashMap<>();

                    Query lastQuery = null;
                    scanner.setColumnTypes(columnTypes);
                    scanner.setQuery(lastQuery);

                    Collection<DataRow> rows;
                    rows = scanner.current(0, 100);
                    LOG.info("Got rows ...");
                }

            } else {
                LOG.error("Connection to {} unavailable", connectionDetails.getZookeeper().getHost());

            }
        } catch (IOException e) {

        }
        return SUCCESS;
    }


    private ConnectionDetails getConnectionDetails(String cluster) {
        ConnectionDetails connectionDetails = new ConnectionDetails(cluster);
        Map<String, String> clusters = GlobalConfig.instance().getClusterConfigurations();
//        if (clusters.size() == 1) {
//            String path = clusters.get(clusters.keySet().iterator().next());
//            connectionDetails = new ConnectionDetails(new File(path).getName());
//        } else if (clusters.size() > 1) {
//            for (String cluster : clusters.keySet()) {
//
//            }
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException ignore) {
//            }
//        } else {
//            connectionDetails = new ConnectionDetails();
//        }
        return connectionDetails;
    }


}
